package com.wlstock.funi.dao;

import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.wlstock.funi.model.PendTradeModel;

public class PendTradeDao {
	
	private Dao<PendTradeModel, Integer> pendTradeDao ;
	private DataBaseHelper helper;
	private static PendTradeDao daoInstance;
	
	@SuppressWarnings("unchecked")
	private PendTradeDao(Context context){
		try {
			helper = DataBaseHelper.getHelper(context);
			pendTradeDao = helper.getDao(PendTradeModel.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static PendTradeDao getInstance(Context mContext){
		if (daoInstance == null) {
			synchronized (PendTradeDao.class) {
				if (daoInstance == null) {
					daoInstance = new PendTradeDao(mContext);
				}
			}
		}
		return daoInstance;
	}
	
	
	public void addOrUpdate(PendTradeModel model){
		PendTradeModel tmpM =  queryModel(model.getApplyNum());
		try {
			if (tmpM == null) {
				pendTradeDao.create(tmpM);
			} else {
				//进行更新操作
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据委托编号查询本地
	 * @param applyNum
	 * @return
	 */
	private PendTradeModel queryModel(String applyNum) {
		try {
			PendTradeModel tmpModel = pendTradeDao.queryBuilder().where().eq("applyNum", applyNum).queryForFirst();
			return tmpModel;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 解析委托序列
	 * @param pendList
	 */
	public void parsePendList(String pendList) {
		Pattern compile = Pattern.compile("记录个数：[0-9]*");
		Matcher matcher = compile.matcher(pendList);
		String totalCount = "";
		while(matcher.find()){
			 totalCount = pendList.substring(matcher.start()+5, matcher.end());
		}
		if (!totalCount.isEmpty() && totalCount.equals("0")) {
			//判断是网络错误还是真的记录为0
			if (pendList.contains("网络错误")) {
				
			}else if (pendList.contains("没有记录")) {
				
			}
			
		}else if (!totalCount.isEmpty()) {
			//总数量不为0
			Document doc = Jsoup.parse(pendList);
			Elements selItems = doc.select("[align=\"right\"]");
			//需要减去最后的一个
			if (selItems.size()-1 == Integer.valueOf(totalCount)) {
				for (Element oddRedItem : selItems) {
					Elements childItems = oddRedItem.children();
					//正确的item
					if (childItems.size() == 19) {
						PendTradeModel model = new PendTradeModel(childItems);
						
					}
					Log.i("TAG",""+ childItems.size());
				}
			}else{
				//数量有误，仍然判定异常
				
			}
		}else {
			//网络异常，可能去到重定向页面
			
		}	
	}
	

	
}
